import { Response } from 'express';
import { AuthenticatedRequest } from '../types/auth';
import { AIQuestionGenerationService } from '../services/aiQuestionGenerationService';
import { ApiError } from '../utils/ApiError';
import { StatusCodes } from '../constants/statusCodes';
import { logger } from '../utils/logger';
import { Role, QuestionType, Difficulty } from '@prisma/client';
import { z } from 'zod';

// 验证Schema
const generationCriteriaSchema = z.object({
  subject: z.string().min(1, '学科不能为空'),
  topic: z.string().min(1, '主题不能为空'),
  difficulty: z.enum([Difficulty.EASY, Difficulty.MEDIUM, Difficulty.HARD]),
  type: z.enum([QuestionType.MULTIPLE_CHOICE, QuestionType.OPEN_ENDED]),
  count: z.number().int().min(1).max(50),
  keywords: z.array(z.string()).optional(),
  excludeIds: z.array(z.string().uuid()).optional()
});

const similarQuestionsSchema = z.object({
  count: z.number().int().min(1).max(10)
});

const knowledgePointsSchema = z.object({
  knowledgePoints: z.array(z.string()).min(1, '至少需要一个知识点'),
  subject: z.string().min(1, '学科不能为空'),
  difficulty: z.enum([Difficulty.EASY, Difficulty.MEDIUM, Difficulty.HARD]),
  type: z.enum([QuestionType.MULTIPLE_CHOICE, QuestionType.OPEN_ENDED]),
  count: z.number().int().min(1).max(50)
});

export const aiQuestionGenerationController = {
  // 生成题目
  async generateQuestions(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      // 验证教师权限
      if (req.user.role !== Role.ADMIN && req.user.role !== Role.TEACHER) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权生成题目');
      }

      const criteria = generationCriteriaSchema.parse(req.body);

      const questions = await AIQuestionGenerationService.generateQuestions(criteria);

      logger.info('题目生成成功', {
        teacherId: req.user.id,
        count: questions.length,
        criteria
      });

      res.json({
        success: true,
        data: questions
      });
    } catch (error) {
      logger.error('题目生成失败', {
        context: 'aiQuestionGenerationController.generateQuestions',
        error
      });
      throw error;
    }
  },

  // 生成相似题目
  async generateSimilarQuestions(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      // 验证教师权限
      if (req.user.role !== Role.ADMIN && req.user.role !== Role.TEACHER) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权生成题目');
      }

      const { questionId } = req.params;
      const { count } = similarQuestionsSchema.parse(req.body);

      const questions = await AIQuestionGenerationService.generateSimilarQuestions(
        questionId,
        count
      );

      logger.info('相似题目生成成功', {
        teacherId: req.user.id,
        originalQuestionId: questionId,
        count: questions.length
      });

      res.json({
        success: true,
        data: questions
      });
    } catch (error) {
      logger.error('相似题目生成失败', {
        context: 'aiQuestionGenerationController.generateSimilarQuestions',
        error
      });
      throw error;
    }
  },

  // 根据知识点生成题目
  async generateByKnowledgePoints(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      // 验证教师权限
      if (req.user.role !== Role.ADMIN && req.user.role !== Role.TEACHER) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权生成题目');
      }

      const { knowledgePoints, ...criteria } = knowledgePointsSchema.parse(req.body);

      const questions = await AIQuestionGenerationService.generateByKnowledgePoints(
        knowledgePoints,
        criteria
      );

      logger.info('根据知识点生成题目成功', {
        teacherId: req.user.id,
        knowledgePoints,
        count: questions.length
      });

      res.json({
        success: true,
        data: questions
      });
    } catch (error) {
      logger.error('根据知识点生成题目失败', {
        context: 'aiQuestionGenerationController.generateByKnowledgePoints',
        error
      });
      throw error;
    }
  }
};
